import {
	config
} from '@/config'
import {
	msg
} from './util'

const baseApi = config.baseApi;

uni.addInterceptor('request', {
	success(res) {
		let data = res.data;
		// 根据返回的code值来做不同的处理(和后端约定)
		switch (data.code) {
			case 401:
				// 未登录 清除已登录状态 跳转登录页
				msg("您还未登录");
				uni.reLaunch({
					url: `/pages/auth/login/login?canBack=false`
				})
				break;
			case 403:
				// 没有权限
				if (data.message) {
					msg(data.message);
				} else {
					msg("未知错误");
				}
				break;
			case 500:
				// 错误
				if (data.message) {
					msg(data.message);
				} else {
					msg("未知错误");
				}
				break;
		}
	},
	fail(res) {
		msg(res.errMsg);
		uni.hideLoading();
		uni.stopPullDownRefresh();
	}
})

// get请求方法 需登录认证
export const get = (url, params) => {
	let accessToken = uni.getStorageSync('accessToken');
	return new Promise((resolve, reject) => {
		uni.request({
			url: `${baseApi}${url}`,
			method: 'get',
			data: params,
			header: {
				'accessToken': accessToken
			},
			success: (res) => {
				resolve(res.data)
			},
			fail: (err) => {
				reject(err)
			}
		});
	});
}

// post请求方法 需登录认证
export const post = (url, params) => {
	let accessToken = uni.getStorageSync('accessToken');
	return new Promise((resolve, reject) => {
		uni.request({
			url: `${baseApi}${url}`,
			method: 'post',
			data: params,
			header: {
				'Content-Type': 'application/x-www-form-urlencoded',
				'accessToken': accessToken
			},
			success: (res) => {
				resolve(res.data)
			},
			fail: (err) => {
				reject(err)
			}
		});
	});
}

// postBody请求方法 需登录认证
export const postBody = (url, params) => {
	let accessToken = uni.getStorageSync('accessToken');
	return new Promise((resolve, reject) => {
		uni.request({
			url: `${baseApi}${url}`,
			method: 'post',
			data: params,
			header: {
				'Content-Type': 'application/json',
				'accessToken': accessToken
			},
			success: (res) => {
				resolve(res.data)
			},
			fail: (err) => {
				reject(err)
			}
		});
	});
}

// get请求方法 无需登录认证
export const getNoAuth = (url, params) => {
	return new Promise((resolve, reject) => {
		uni.request({
			url: `${baseApi}${url}`,
			method: 'get',
			data: params,
			success: (res) => {
				resolve(res.data)
			},
			fail: (err) => {
				reject(err)
			}
		});
	});
}

// post请求方法 无需登录认证
export const postNoAuth = (url, params) => {
	return new Promise((resolve, reject) => {
		uni.request({
			url: `${baseApi}${url}`,
			method: 'post',
			data: params,
			header: {
				'Content-Type': 'application/x-www-form-urlencoded',
			},
			success: (res) => {
				resolve(res.data)
			},
			fail: (err) => {
				reject(err)
			}
		});
	});
}

// postBody请求方法 无需登录认证
export const postBodyNoAuth = (url, params) => {
	return new Promise((resolve, reject) => {
		uni.request({
			url: `${baseApi}${url}`,
			method: 'post',
			data: params,
			header: {
				'Content-Type': 'application/json',
			},
			success: (res) => {
				resolve(res.data)
			},
			fail: (err) => {
				reject(err)
			}
		});
	});
}
